package n4_线程安全;


import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 可变 对象值 不能做 锁
 */
@Slf4j(topic = "c.T3")
public class T3_可变线程不能做锁 {

    private static Integer i = 0;
    public static void main(String[] args) throws InterruptedException {

        List<Thread> list = new ArrayList<>();
        // 创建两个 -线程-
        for (int j = 0; j < 2; j++) {

            Thread thread = new Thread(() -> {
                for (int k = 0; k < 5000; k++) {
                    synchronized (i) { // Integer i 不能锁，它一直在变化
                        i++;
                        log.debug("+++++" + i);

                    }
                }
            }, "" + j);
            list.add(thread);
        }

        list.stream().forEach(t -> t.start());
        list.stream().forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        log.debug("{}", i);
    }

}
